package dongchel.vrp.immunes;

import java.util.ArrayList;
import java.util.List;

import dongchel.vrp.entity.Solution;
import dongchel.vrp.general.CompareObject;

public class Memory {
	private List<Solution> memoryPopulation;
	private int populationSize = 100;
	private List<Solution> initialMemoryPopulation = new ArrayList<Solution>();
	private int memorySize = 10;
	
	//construct the initial 
	public Memory(List<Solution> memoryPopulation){
		this.memoryPopulation = memoryPopulation;
	}
	
	public List<Solution> constructMemory(List<CompareObject> compareObjectList) {
		int j = 0;
		Solution solu = (Solution)compareObjectList.get(j).getObject();
		initialMemoryPopulation.add((Solution)solu.clone());
		int memoryNumber = 1;
		boolean isequal = false;
		while(j<compareObjectList.size()-1&&memoryNumber<memorySize) {
			j++;
			solu = (Solution)compareObjectList.get(j).getObject();
			for(int k=0;k<initialMemoryPopulation.size();k++){  //test if the solu is the same with any solu in initialMemory 
				//compare the second element--distance
				if(initialMemoryPopulation.get(k).getObjectiveValue().getObjectiveList().get(1)
						==solu.getObjectiveValue().getObjectiveList().get(1)) {
					isequal = true;
					break;
				}
			}
			if(isequal == false) {
				initialMemoryPopulation.add((Solution)solu.clone());
				memoryNumber++;
			}
		}
		return initialMemoryPopulation;
	}

	public void updateMemory(List<Solution> newComing) {
		boolean isequal = false;
		for(int i=0;i<newComing.size();i++){
			for(int j=0;j<memoryPopulation.size();j++) {
				if(Math.abs(newComing.get(i).getObjectiveValue().getObjectiveList().get(1)
						-memoryPopulation.get(j).getObjectiveValue().getObjectiveList().get(1))<0.1) {
					isequal = true;
					break;
				}
			}
			if(isequal == false) {
				memoryPopulation.add(newComing.get(i));
			}
		}
		SortPopulation memorySort = new SortPopulation(memoryPopulation);
		memorySort.sortPopulation();
		for(int i=0;i<memoryPopulation.size();i++) {
			memoryPopulation.set(i, (Solution)memorySort.getCompareObjectList().get(i).getObject());
		}

		//come back to original size
		while(memoryPopulation.size()>populationSize) {
			memoryPopulation.remove(populationSize);

		}

	}

	public List<Solution> getMemoryPopulation() {
		return memoryPopulation;
	}

	public void setMemoryPopulation(List<Solution> memoryPopulation) {
		this.memoryPopulation = memoryPopulation;
	}
}
